package dao.impl;

import dao.UserDao;
import entity.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import pstmt.UserpstmtCreator;
import rowmapper.UserRowMapper;

import java.util.List;

public class UserDaoImpl implements UserDao {

    private JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void insert(User user) {
        String sql = new StringBuffer()
                .append(" insert into t_user")
                .append("(username,password,phone,address) ")
                .append(" values")
                .append("(?,?,?,?)").toString();
        jdbcTemplate.update(sql,user.getUsername(),user.getPassword(),user.getPhone(),user.getAddress());
    }

    @Override
    public void deleteById(Integer id) {

    }

    @Override
    public void update(User user) {

    }

    @Override
    public User selectById(Integer id) {
        String sql = new StringBuffer()
                .append("select * from t_user where id = ?").toString();
        List<User> users = jdbcTemplate.query(sql, new Object[]{id}, new UserRowMapper());

        return users.isEmpty()?null:users.get(0);
    }

    @Override
    public List<User> selectAll() {
        return null;
    }

    @Override
    public Long insertReturnPrimaryKey(User user) {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        String sql = new StringBuffer()
                .append("insert into t_user ")
                .append("(username,password,phone,address)")
                .append(" values ")
                .append("(?,?,?,?)").toString();
        jdbcTemplate.update(new UserpstmtCreator(sql,user),keyHolder);

        return (Long) keyHolder.getKey();
    }
}
